package com.bungarus.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SmartTestClient {

    private final static String smartRequestUrl = "http://smart.bungarus.com:9090/api/smart/v1.0/routes";

    public List<String> getIpList() {
        List<String> result = new ArrayList<String>();
        try{
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            String resp = httpGet(smartRequestUrl, params);
            ObjectMapper mapper = new ObjectMapper();
            result = mapper.readValue(resp, List.class);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally {

        }
        return result;
    }

    public String httpGet(String url, MultiValueMap<String, String> params) throws IOException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3*1000);
        requestFactory.setReadTimeout(2*1000);
        RestTemplate client = new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);
        // exec http request
        ResponseEntity<String> response = client.exchange(url, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
    }
}
